/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/ccjzxyxt">ccjzxyxt</a> All rights reserved.
 */
package cn.net.dckj.modules.biz.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.net.dckj.common.utils.excel.ExportExcel;
import cn.net.dckj.common.utils.excel.ImportExcel;
import cn.net.dckj.modules.biz.common.EducationUtils;
import cn.net.dckj.modules.biz.entity.*;
import cn.net.dckj.modules.biz.service.BizSchoolCalendarService;
import cn.net.dckj.modules.biz.service.ClassStudentTimeService;
import cn.net.dckj.modules.sys.entity.Office;
import cn.net.dckj.modules.sys.entity.User;
import cn.net.dckj.modules.sys.service.OfficeService;
import cn.net.dckj.modules.sys.service.SystemService;
import cn.net.dckj.modules.sys.utils.DictUtils;
import com.google.common.collect.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.net.dckj.common.config.Global;
import cn.net.dckj.common.persistence.Page;
import cn.net.dckj.common.web.BaseController;
import cn.net.dckj.common.utils.StringUtils;
import cn.net.dckj.modules.biz.service.BizStudentTimetableService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 学生课表信息Controller
 *
 * @author xzy
 * @version 2019-04-15
 */
@Controller
@RequestMapping(value = "${adminPath}/biz/bizStudentTimetable")
public class BizStudentTimetableController extends BaseController {

    @Autowired
    private BizStudentTimetableService bizStudentTimetableService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private BizSchoolCalendarService bizSchoolCalendarService;
    @Autowired
    private ClassStudentTimeService classStudentTimeService;

    @ModelAttribute
    public BizStudentTimetable get(@RequestParam(required = false) String id) {
        BizStudentTimetable entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = bizStudentTimetableService.get(id);
        }
        if (entity == null) {
            entity = new BizStudentTimetable();
        }
        return entity;
    }

    @RequiresPermissions("biz:bizStudentTimetable:view")
    @RequestMapping(value = {"list", ""})
    public String list(BizStudentTimetable bizStudentTimetable, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<BizStudentTimetable> page = bizStudentTimetableService.findPage(new Page<BizStudentTimetable>(request, response), bizStudentTimetable);
        model.addAttribute("page", page);
        return "modules/biz/bizStudentTimetableList";
    }

    @RequiresPermissions("biz:bizStudentTimetable:view")
    @RequestMapping(value = "form")
    public String form(BizStudentTimetable bizStudentTimetable, Model model) {
        User user = new User();
        user.setUserType("2");
        List<User> userlist = systemService.findUser(user);
        model.addAttribute("userlist", userlist);
        user.setUserType("3");
        List<User> studentlist = systemService.findUser(user);
        model.addAttribute("userlist", userlist);
        model.addAttribute("studentlist", studentlist);
        model.addAttribute("bizStudentTimetable", bizStudentTimetable);
        return "modules/biz/bizStudentTimetableForm";
    }

    @RequiresPermissions("biz:bizStudentTimetable:edit")
    @RequestMapping(value = "save")
    public String save(BizStudentTimetable bizStudentTimetable, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, bizStudentTimetable)) {
            return form(bizStudentTimetable, model);
        }
//		if(StringUtils.isNotEmpty(bizStudentTimetable.getClassid())){
//			Office office = officeService.get(bizStudentTimetable.getClassId());
//			if(office==null){
//				bizStudentTimetable.setClassName("");
//			}else{
//				bizStudentTimetable.setClassName(office.getName());
//			}
//		}
        String schoolYear = bizStudentTimetable.getSchoolyear();
        if (StringUtils.isBlank(schoolYear)) {
            addMessage(redirectAttributes, "保存学生课表信息失败，原因：学年信息为空！");
            return "redirect:" + Global.getAdminPath() + "/biz/bizTeacherTimetable/?repage";
        }
        BizSchoolCalendar bizSchoolCalendar = bizSchoolCalendarService.getSchoolCalendar(schoolYear);
        if (bizSchoolCalendar == null) {
            addMessage(redirectAttributes, "保存学生课表信息失败，原因：未查询到校历信息！");
            return "redirect:" + Global.getAdminPath() + "/biz/bizTeacherTimetable/?repage";
        }
        // 判断修改or新增
        String studentTimetableId = bizStudentTimetable.getId();
        if (StringUtils.isNotBlank(studentTimetableId)) {
            // 修改状态，判断修改字段是否影响课程时间
            BizStudentTimetable oldEntity = bizStudentTimetableService.get(studentTimetableId);
            if (!oldEntity.getSchoolyear().equals(bizStudentTimetable.getSchoolyear()) ||
                    !oldEntity.getTerm().equals(bizStudentTimetable.getTerm()) ||
                    !oldEntity.getWeekstart().equals(bizStudentTimetable.getWeekstart()) ||
                    !oldEntity.getWeekend().equals(bizStudentTimetable.getWeekend()) ||
                    !oldEntity.getSection().equals(bizStudentTimetable.getSection()) ||
                    !oldEntity.getWeekday().equals(bizStudentTimetable.getWeekday())
                    ) {
                // 新增上课时间
                AddStudentClassTime(bizSchoolCalendar, bizStudentTimetable);
            }
            bizStudentTimetableService.save(bizStudentTimetable);
        } else {
            bizStudentTimetableService.save(bizStudentTimetable);
            // 新增上课时间
            AddStudentClassTime(bizSchoolCalendar, bizStudentTimetable);
        }
        addMessage(redirectAttributes, "保存学生课表信息成功");
        return "redirect:" + Global.getAdminPath() + "/biz/bizStudentTimetable/?repage";
    }

    @RequiresPermissions("biz:bizStudentTimetable:edit")
    @RequestMapping(value = "delete")
    public String delete(BizStudentTimetable bizStudentTimetable, RedirectAttributes redirectAttributes) {
        bizStudentTimetableService.delete(bizStudentTimetable);
        addMessage(redirectAttributes, "删除学生课表信息成功");
        return "redirect:" + Global.getAdminPath() + "/biz/bizStudentTimetable/?repage";
    }

    /**
     * 下载导入学生课表数据模板
     *
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("biz:bizStudentTimetable:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "学生课表数据导入模板.xlsx";
            List<BizStudentTimetable> list = Lists.newArrayList();
            BizStudentTimetable bizStudentTimetable = new BizStudentTimetable();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            bizStudentTimetable.setSchoolyear("2019");
            bizStudentTimetable.setTerm("1");
            bizStudentTimetable.setWeekstart("1");
            bizStudentTimetable.setWeekend("13");
            bizStudentTimetable.setWeekend("1");
            bizStudentTimetable.setSection("4");
            bizStudentTimetable.setCoursename("钢结构施工技术");
            bizStudentTimetable.setTeachername("教师姓名");
            bizStudentTimetable.setTeacheridcard("220102xxxx0808xxxx");
            //bizStudentTimetable.se("班级名称1,班级名称2");
            bizStudentTimetable.setAddress("DX511");
            list.add(bizStudentTimetable);
            new ExportExcel("学生课表数据", BizStudentTimetable.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/biz/bizStudentTimetable/list?repage";
    }

    /**
     * 导入学生课表数据
     *
     * @param file
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("biz:bizStudentTimetable:edit")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(BizStudentTimetable biz, MultipartFile file, RedirectAttributes redirectAttributes) {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/biz/bizStudentTimetable/list?repage";
        }
        if (StringUtils.isEmpty(biz.getClassid()) || StringUtils.isEmpty(biz.getClassname())) {
            addMessage(redirectAttributes, "请先在左侧选择班级在进行导入学生课表信息操作！");
            return "redirect:" + adminPath + "/biz/bizStudentTimetable/list?repage";
        }
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<BizStudentTimetable> list = ei.getDataList(BizStudentTimetable.class);
            for (BizStudentTimetable bizStudentTimetable : list) {
                try {
                    if (StringUtils.isEmpty(bizStudentTimetable.getSchoolyear()) ||
                            StringUtils.isEmpty(bizStudentTimetable.getTerm()) ||
                            StringUtils.isEmpty(bizStudentTimetable.getWeekstart()) ||
                            StringUtils.isEmpty(bizStudentTimetable.getWeekend()) ||
                            StringUtils.isEmpty(bizStudentTimetable.getWeekday()) ||
                            StringUtils.isEmpty(bizStudentTimetable.getSection()) ||
                            StringUtils.isEmpty(bizStudentTimetable.getTeachername()) ||
                            StringUtils.isEmpty(bizStudentTimetable.getAddress()) ||
                            StringUtils.isEmpty(bizStudentTimetable.getTeacheridcard())) {
                        failureMsg.append("<br/> 班级" + biz.getClassname() + " 的学年、学期、学周开始、学周结束、星期几、课节、课程名称、上课老师姓名、上课老师身份证号、上课地址均不能为空; ");
                        failureNum++;
                        continue;
                    }
                    if (checkIdCard(bizStudentTimetable.getTeacheridcard())) {
                        bizStudentTimetable.setTeacheridcard(bizStudentTimetable.getTeacheridcard());
                        successNum++;
                    } else {
                        failureMsg.append("<br/> 班级" + biz.getClassname() + " 的上课老师身份证号格式不正确; ");
                        failureNum++;
                        continue;
                    }
                } catch (Exception ex) {
                    failureMsg.append("<br/> 班级 " + biz.getClassname() + " 的课表信息导入失败：" + ex.getMessage());
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条数据，导入信息如下：");
            } else {
                for (BizStudentTimetable bizStudentTimetable : list) {
                    try {
                        bizStudentTimetable.setClassid(biz.getClassid());
                        bizStudentTimetable.setClassname(biz.getClassname());
                        bizStudentTimetableService.save(bizStudentTimetable);
                        BizSchoolCalendar bizSchoolCalendar = bizSchoolCalendarService.getSchoolCalendar(bizStudentTimetable.getSchoolyear());
                        // 新增上课时间
                        AddStudentClassTime(bizSchoolCalendar,bizStudentTimetable);
                        successNum++;
                    } catch (Exception e) {
                        failureMsg.append("<br/>课表 " + bizStudentTimetable.getClassname() + " 导入失败：" + e.getMessage());
                        failureNum++;
                    }

                }
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条数据" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入数据失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/biz/bizStudentTimetable/list?repage";
    }

    @RequiresPermissions("biz:bizStudentTimetable:view")
    @RequestMapping(value = {"index"})
    public String index(BizStudentTimetable bizStudentTimetable, Model model) {
        return "modules/biz/studentIndex";
    }

    /**
     * 身份证校验
     */
    public static final Boolean checkIdCard(String idCard) {
        // 检测身份证是否包含中文
        Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher aMatcher = pattern.matcher(idCard);
        boolean isZH = aMatcher.find();
        // 检测身份证位数是否是正常是法定位数（15，17，18）
        boolean amount = (idCard.length() == 15 || idCard.length() == 17 || idCard.length() == 18);
        // 两方面条件都满足时，返回true
        boolean existed = (isZH == false) && (amount == true);
        return existed;
    }


    //新增学生上课时间
    private void AddStudentClassTime(BizSchoolCalendar bizSchoolCalendar, BizStudentTimetable bizStudentTimetable) {
        // 删除原有上课时间
        classStudentTimeService.deleteAll(bizStudentTimetable.getId());
        ClassTime delClassTime = new ClassTime();
        delClassTime.setTeacherTimetableId(bizStudentTimetable.getId());
        // 换成新写方法
//        classTimeService.delete(delClassTime);
        // 根据课节，换算上课开始和结束时间
        String section = bizStudentTimetable.getSection();
        String startTime;   //上课开始时间
        String endTime;     //上课结束时间
        String time = DictUtils.getDictEntity("section", section).getRemarks();
        if (StringUtils.isNotEmpty(time)) {
            String[] strs = time.split("-");
            startTime = strs[0];
            endTime = strs[1];
        } else {
            if ("1".equals(section)) {
                startTime = "08:25:00";
                endTime = "09:50:00";
            } else if ("2".equals(section)) {
                startTime = "10:10:00";
                endTime = "11:35:00";
            } else if ("3".equals(section)) {
                startTime = "13:15:00";
                endTime = "14:40:00";
            } else {
                startTime = "15:00:00";
                endTime = "16:25:00";
            }
        }
        // 确定学期开始时间
        Date termStart;
        String term = bizStudentTimetable.getTerm();
        if ("1".equals(term)) {
            termStart = bizSchoolCalendar.getFirstClassStartDate();
        } else {
            termStart = bizSchoolCalendar.getSecondClassStartDate();
        }
        int weekStart = Integer.parseInt(bizStudentTimetable.getWeekstart());
        int weekEnd = Integer.parseInt(bizStudentTimetable.getWeekend());
        // 上课星期几
        int weekday = Integer.parseInt(bizStudentTimetable.getWeekday() == null ? "7" : bizStudentTimetable.getWeekday());
        // 合成真正上课开始和结束时间并保存
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = weekStart; i <= weekEnd; i++) {
            ClassStudentTime classStudentTime = new ClassStudentTime();
            classStudentTime.setStudentTimetableId(bizStudentTimetable.getId());
            // 获取上课日期
            Date date = EducationUtils.getCourseDate(termStart, i, weekday);
            String dateStr = sdf.format(date);
            try {
                classStudentTime.setCourseStartTime(format.parse(dateStr + " " + startTime));
                classStudentTime.setCourseEndTime(format.parse(dateStr + " " + endTime));
                classStudentTimeService.save(classStudentTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}